package com.example.sakurasay.passwordbook.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.example.sakurasay.databinding.FragmentIndependentPasswordBinding
import com.example.sakurasay.passwordbook.viewmodels.IndependentPasswordViewModel
import kotlinx.coroutines.launch

class IndependentPasswordFragment : Fragment() {

    private var _binding: FragmentIndependentPasswordBinding? = null
    private val binding get() = _binding!!

    private val viewModel: IndependentPasswordViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentIndependentPasswordBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val passwordAdapter = IndependentPasswordAdapter()
        binding.recyclerViewPasswords.adapter = passwordAdapter

        binding.fabAddPassword.setOnClickListener {
            // Open the bottom sheet
            AddEditIndependentPasswordSheet().show(childFragmentManager, "AddEditPasswordSheet")
        }

        lifecycleScope.launch {
            viewModel.allEntries.collect { entries ->
                passwordAdapter.submitList(entries)
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}